package com.j48.entrancegurad.config;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
public class LoginFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //开始进入请求地址拦截
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=utf-8");
        if(!StringUtils.isEmpty(session.getAttribute("admin"))){//只有在登录之后才能进入
            return true;
        }
        else{//没有登录的情况下，无法访问相关页面
            PrintWriter printWriter = response.getWriter();
            printWriter.write("<div style='font-size:30px;width: 400px;position: absolute;margin-left: -120px;margin-top: -100px;top: 30%;left: 50%;display: block;z-index: 2000;'><div style='margin-left:-70px;margin-top:-30px;'>你还未登录，请先登录!</div>" +
                    "<a href='loginofall' style='width: 400px;position: absolute;margin-left: -350px;margin-top: 20px;top: 50%;left: 50%;display: block;z-index: 2000;background-color: #4CAF50; /* Green */\n" +
                    "    border: none;\n" +
                    "    color: white;\n" +
                    "    padding: 15px 32px;\n" +
                    "    text-align: center;\n" +
                    "    text-decoration: none;\n" +
                    "    display: inline-block;\n" +
                    "    font-size: 16px;'>返回登录</a></div>");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //处理请求完成后视图渲染之前的处理操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //视图渲染之后的操作
    }
}
